package com.benew.ntt.player

import android.content.Context
import com.google.android.exoplayer2.util.Log
import java.util.concurrent.LinkedBlockingQueue

class NttAudioPlayer : IAudioBase {

    private var mPlayer: IPlayer? = null
    private var mAudioPlayerListener: IAudioPlayListener? = null
    private var mAudioId: Long = 0
    private var mUrl: String? = null
    private val mAudioLock = Any()


    override fun init(context: Context) {
        mPlayer = NttExoPlayer(context).apply {
            setPlayListener(listener)
        }
    }

    override fun release() {
        mPlayer?.release()
        mAudioId = 0
        mUrl = null
    }


    fun setAudioPlayListener(audioPlayerListener: IAudioPlayListener?) {
        mAudioPlayerListener = audioPlayerListener
    }


    fun playAudios(audios: List<AudioItem>) {
        synchronized(mAudioLock) {
            mAudioQueue.clear()
            mAudioQueue.addAll(audios)
            playAudio(false)
        }
    }

    fun resume() {
        mPlayer?.resume()
    }

    fun pause() {
        mPlayer?.pause()
    }

    fun isPlaying(): Boolean {
        return mPlayer?.isPlaying() ?: false
    }

    fun stop() {
        mPlayer?.stop()
        mAudioPlayerListener?.onStop(mUrl, mAudioId)
        synchronized(mAudioLock) {
            mAudioQueue.clear()
        }
    }

    private fun playAudio(isMediaChanged: Boolean) {
        mAudioQueue.poll()?.run {
            if (isMediaChanged) {
                mAudioPlayerListener?.onMediaChanged(this)
            }
            mUrl = this.url
            mAudioId = this.id
            mPlayer?.play(this)
        }
    }

    private val mAudioQueue by lazy {
        LinkedBlockingQueue<AudioItem>()
    }

    private val listener = object : IPlayerListener {
        override fun onPrepared(url: String?) {
            mAudioPlayerListener?.onPrepare(url, mAudioId)
        }

        override fun onComplete(url: String?) {
            Log.i("NttAudioPlayer", "play complete")
            synchronized(mAudioLock) {
                mAudioQueue.takeIf {
                    it.isNotEmpty()
                }?.run {
                    playAudio(true)
                } ?: mAudioPlayerListener?.onComplete(url, mAudioId)
            }
        }

        override fun onError(url: String?, code: Int, msg: String?) {
            mAudioPlayerListener?.onError(url, mAudioId, code, msg)
        }

        override fun onPause() {
            mAudioPlayerListener?.onPause()
        }

        override fun onPlaying() {
            mAudioPlayerListener?.onPlaying()
        }

    }


}